package com.wjr.braveheart.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class PreferencesUtils {
    private SharedPreferences mPreferences = null;
    private SharedPreferences.Editor mEditor = null;
    private static volatile PreferencesUtils sInstance;

    public static PreferencesUtils getInstance() {
        if (sInstance == null) {
            synchronized (PreferencesUtils.class) {
                if (sInstance == null) {
                    // 使用双重同步锁
                    sInstance = new PreferencesUtils();
                }
            }
        }
        return sInstance;
    }

    /**
     * 问题在于，这个Context哪来的我们不能确定，很大的可能性，你在某个Activity里面为了方便，直接传了个this;
     * 这样问题就来了，我们的这个类中的sInstance是一个static且强引用的，在其内部引用了一个Activity作为Context，也就是说，
     * 我们的这个Activity只要我们的项目活着，就没有办法进行内存回收。而我们的Activity的生命周期肯定没这么长，造成了内存泄漏。
     * 所以这里使用context.getApplicationContext()
     */
    public void init(Context context) {
        mPreferences = PreferenceManager.getDefaultSharedPreferences(context
                .getApplicationContext());
    }

    private PreferencesUtils() {

    }

    /**
     * 保存数据 , 所有的类型都适用
     *
     * @param key
     * @param object
     */
    public synchronized void saveParam(String key, Object object) {
        if (mEditor == null)
            mEditor = mPreferences.edit();
        // 得到object的类型
        String type = object.getClass().getSimpleName();
        switch (type) {
            case "String":
                // 保存String 类型
                mEditor.putString(key, (String) object);
                break;
            case "Integer":
                // 保存integer 类型
                mEditor.putInt(key, (Integer) object);
                break;
            case "Boolean":
                // 保存 boolean 类型
                mEditor.putBoolean(key, (Boolean) object);
                break;
            case "Float":
                // 保存float类型
                mEditor.putFloat(key, (Float) object);
                break;
            case "Long":
                // 保存long类型
                mEditor.putLong(key, (Long) object);
                break;
            default:
                //保存Object
                saveObject(key, object);
                break;
        }
        mEditor.apply();
    }

    /**
     * 保存Object
     *
     * @param key
     * @param object
     */
    private void saveObject(String key, Object object) {
        if (!(object instanceof Serializable)) {
            throw new IllegalArgumentException(object.getClass().getName() + "must implements serializable interface !");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            String productBase64 = Base64.encodeToString(
                    baos.toByteArray(), Base64.DEFAULT);
            oos.close();
            baos.close();
            mEditor.putString(key, productBase64);
            Log.d(this.getClass().getSimpleName(), "save object success");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(this.getClass().getSimpleName(), "save object error");
        }
    }

    /**
     * 移除信息
     */
    public synchronized void remove(String key) {
        if (mEditor == null)
            mEditor = mPreferences.edit();
        mEditor.remove(key);
        mEditor.apply();
    }


    /**
     * 得到保存数据的方法，所有类型都适用
     *
     * @param key
     * @param defaultObject
     * @return
     */
    public Object getParam(String key, Object defaultObject) {
        if (defaultObject == null) {
            return getObject(key);
        }

        String type = defaultObject.getClass().getSimpleName();
        switch (type) {
            case "String":
                return mPreferences.getString(key, (String) defaultObject);
            case "Integer":
                return mPreferences.getInt(key, (Integer) defaultObject);
            case "Boolean":
                return mPreferences.getBoolean(key, (Boolean) defaultObject);
            case "Float":
                return mPreferences.getFloat(key, (Float) defaultObject);
            case "Long":
                return mPreferences.getLong(key, (Long) defaultObject);
            default:
                return getObject(key);
        }
    }

    /**
     * 获取Object
     *
     * @param key
     * @return
     */
    private Object getObject(String key) {
        String wordBase64 = mPreferences.getString(key, "");
        byte[] base64 = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(base64);
        try {
            ObjectInputStream bis = new ObjectInputStream(bais);
            Object object = bis.readObject();
            bis.close();
            bais.close();
            Log.d(this.getClass().getSimpleName(), "Get object success");
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(this.getClass().getSimpleName(), "Get object is error");
        }
        return null;
    }

    /**
     * 清空
     */
    public void clear() {
        if (mEditor == null)
            mEditor = mPreferences.edit();
        mEditor.clear();
        mEditor.apply();
    }
}